/*
 * @Author: liangliang
 * @Date: 2023-05-18 15:40:29
 * @LastEditors: yusha
 * @LastEditTime: 2023-08-25 10:14:43
 * @Description: 线上bug登记
 */

import React, { useState } from 'react';
import { useAntdTable } from 'ahooks';
import dayjs from 'dayjs';
import { Button, Form, Input, Row, message, Space, DatePicker, Table, Modal, Select, Col } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { useFormModal } from '@/hooks/useFormModal';
import { bugRegisterEdit, bugRegisterQryPage, bugRegisterAdd, demandReportAdd } from '@/config/request/manage';

import EditSupplierInfo from './module/EditSupplierInfo';
import EditSupplierInfo1 from '@/container/manager/demand/module/EditSupplierInfo';
import './index.scss';

const SupplierList: React.FC = () => {
    const [form] = Form.useForm();
    const formModalSupplierInfo = useFormModal();
    const formModalSupplierInfo1 = useFormModal();
    const [rowItem, setRowItem] = useState<any>();
    const [isEditInfo, setIsEditInfo] = useState(false);
    const [isBugfix, setIsBugfix] = useState(false);

    const { tableProps, search } = useAntdTable(
        async ({ pageSize, current: pageNum }) => {
            const { createTime } = form.getFieldsValue();
            const params = {
                ...form.getFieldsValue(),
                startTime: createTime?.[0]?.format('YYYY-MM-DD 00:00:00'),
                endTime: createTime?.[1]?.format('YYYY-MM-DD 23:59:59'),
                pageNum,
                pageSize,
                // supplierType
            };
            delete params.createTime;
            const res = await bugRegisterQryPage(params);
            return {
                total: res.data.data?.total ?? 0,
                list: res.data.data?.list ?? [],
            };
        },
        { defaultPageSize: 10, form }
    );

    const columns: ColumnsType<any> = [
        // {
        //     title: '序号',
        //     dataIndex: 'key',
        //     key: 'key',
        //     width: 20,
        //     render: (value, record, index) => <span>{index + 1}</span>
        // },
        // {
        //     title: 'bugID',
        //     dataIndex: 'bugId',
        //     key: 'bugId',
        //     width: 40
        // },
        {
            title: <span style={{}}>故障类型</span>,
            dataIndex: 'bugType',
            key: 'bugType',
            width: 42,
            // render: (text) => <span>{['', '技术自查', '业务反馈', '数据监控', '自动化跑出', '其它'][text]}</span>,
        },
        {
            title: '故障等级',
            dataIndex: 'bugLevel',
            key: 'bugLevel',
            width: 42,
            // render: (text) => <span>{['P0', 'P1', 'P2', 'P3', 'P4', 'P5'][text]}</span>,
        },
        {
            title: '故障状态',
            dataIndex: 'bugStatus',
            key: 'bugStatus',
            width: 42,
            render: (text: string) => {
                if (text === '待处理') {
                    return <span style={{ color: 'red' }}>{[text]}</span>;
                }
                if (text === '已解决') {
                    return <span style={{ color: 'green' }}>{[text]}</span>;
                }
                if (text === '转产品') {
                    return <span style={{ color: 'blue' }}>{[text]}</span>;
                }
                if (text === '处理中') {
                    return <span style={{ color: 'blue' }}>{[text]}</span>;
                }
                return <span style={{ color: 'black' }}>{text}</span>;

            },
        },
        {
            title: '所属应用',
            dataIndex: 'belongApplication',
            key: 'belongApplication',
            width: 42,
            // render: (text) => <span>{['', '订单', '采购', '仓库', '商品', '结算', 'api', '营销', '会员', '前端', '其他'][text]}</span>,
        },
        {
            title: '故障时间',
            dataIndex: 'bugTime',
            key: 'bugTime',
            width: 52,
            render: (text) => dayjs(text).format('YYYY-MM-DD'),
        },
        {
            title: '故障描述',
            dataIndex: 'bugDescribe',
            key: 'bugDescribe',
            width: 200,
        },
        {
            title: '故障原因',
            dataIndex: 'bugReason',
            key: 'bugReason',
            width: 200,
        },
        // {
        //     title: '云效链接',
        //     dataIndex: 'yunxiaoLink',
        //     key: 'yunxiaoLink',
        //     width: 100
        // },
        {
            title: '故障跟进人',
            dataIndex: 'bugFlower',
            key: 'bugFlower',
            width: 60,
        },
        {
            title: '关联项目',
            dataIndex: 'linkProject',
            key: 'linkProject',
            width: 80,
        },

        // {
        //     title: '自动化是否覆盖',
        //     dataIndex: 'autoCheckFlag',
        //     key: 'autoCheckFlag',
        //     width: 50,
        //     render: (text) => <span>{['', '已覆盖', '未覆盖', '难以覆盖'][text]}</span>,
        // },
        {
            title: '开发人员',
            dataIndex: 'developer',
            key: 'developer',
            width: 42,
        },
        {
            title: '测试人员',
            dataIndex: 'tester',
            key: 'tester',
            width: 42,
        },
        // {
        //     title: '创建时间',
        //     dataIndex: 'createTime',
        //     key: 'createTime',
        //     width: 100,
        // },
        // {
        //     title: '更新时间',
        //     dataIndex: 'updateTime',
        //     key: 'updateTime',
        //     width: 100,
        // },
        {
            title: '备注',
            dataIndex: 'remark',
            key: 'remark',
            width: 200,
        },
        {
            title: '操作',
            key: 'action',
            fixed: 'right',
            width: 100,
            render: (_: any, record: any) => {
                return (
                    <Space size="middle" className="flex-col">
                        <Button
                            type="link"
                            size="small"
                            onClick={() => {
                                setRowItem(record);
                                setIsEditInfo(true);
                                formModalSupplierInfo.modal.open();
                            }}
                        >
                            修改
                        </Button>
                        {
                            record.bugStatus === '处理中' && (
                                <Button
                                    type="link"
                                    size="small"
                                    disabled={record.demand}
                                    onClick={() => {
                                        setRowItem(record);
                                        setIsEditInfo(true);
                                        setIsBugfix(true);
                                        formModalSupplierInfo1.modal.open();
                                    }}
                                >
                                    转bugfix
                                </Button>
                            )
                        }
                    </Space>
                );
            },
        },
    ];

    // 新增/修改供应商信息
    const editSupplierInfo = async () => {
        const params = await formModalSupplierInfo.form.validateFields();
        params.bugTime = dayjs(params.bugTime).format('YYYY-MM-DD 00:00:00');
        try {
            const response = isEditInfo ?
                await bugRegisterEdit({
                    ...rowItem,
                    ...params,
                }) :
                await bugRegisterAdd(params);
            if (response.data.code === 200) {
                message.success('保存成功！');
                formModalSupplierInfo.modal.close();
                search.submit();
            }
        } catch (error: any) {
            message.error(error);
        }
    };

    const editDemandInfo = async () => {
        try {
            const params = await formModalSupplierInfo1.form.validateFields();

            params.demandReviewDate = params.demandReviewDate ? dayjs(params.demandReviewDate).format('YYYY-MM-DD 00:00:00') : '';
            params.technicalProposalDate = params.technicalProposalDate ? dayjs(params.technicalProposalDate).format('YYYY-MM-DD 00:00:00') : '';
            params.tcProposalDate = params.tcProposalDate ? dayjs(params.tcProposalDate).format('YYYY-MM-DD 00:00:00') : '';
            params.submitApplicationDate = params.submitApplicationDate ? dayjs(params.submitApplicationDate).format('YYYY-MM-DD 00:00:00') : '';
            params.joinDebuggerDateStart = params.joinDebuggerDateStart ? dayjs(params.joinDebuggerDateStart).format('YYYY-MM-DD 00:00:00') : '';
            params.joinDebuggerDateEnd = params.joinDebuggerDateEnd ? dayjs(params.joinDebuggerDateEnd).format('YYYY-MM-DD 00:00:00') : '';
            params.testEnvironmentDateStart = params.testEnvironmentDateStart ? dayjs(params.testEnvironmentDateStart).format('YYYY-MM-DD 00:00:00') : '';
            params.testEnvironmentDateEnd = params.testEnvironmentDateEnd ? dayjs(params.testEnvironmentDateEnd).format('YYYY-MM-DD 00:00:00') : '';
            params.preEnvironmentDateStart = params.preEnvironmentDateStart ? dayjs(params.preEnvironmentDateStart).format('YYYY-MM-DD 00:00:00') : '';
            params.preEnvironmentDateEnd = params.preEnvironmentDateEnd ? dayjs(params.preEnvironmentDateEnd).format('YYYY-MM-DD 00:00:00') : '';
            params.publishDate = params.publishDate ? dayjs(params.publishDate).format('YYYY-MM-DD 00:00:00') : '';
            params.finalPublishDate = params.finalPublishDate ? dayjs(params.finalPublishDate).format('YYYY-MM-DD 00:00:00') : '';
            params.smokeDateStart = params.smokeDateStart ? dayjs(params.smokeDateStart).format('YYYY-MM-DD 00:00:00') : '';
            params.smokeDateEnd = params.smokeDateEnd ? dayjs(params.smokeDateEnd).format('YYYY-MM-DD 00:00:00') : '';
            params.bugId = rowItem.bugId;
            
            const response = await demandReportAdd(params);
            console.log(params);
            if (response.data.code === 200) {
                message.success('保存成功！');
                formModalSupplierInfo1.modal.close();
                search.submit();
                await bugRegisterEdit({...rowItem,demand: true,});
            }
        } catch (error: any) {
            // message.error(error);
            console.error("必填项未填：", error);
        }
    };


    return (
        <div className="bg-white p-2.5">
            <Form form={form} name="supplierList_search">
                <Row>
                    <Col span={6}>
                        <Form.Item label="故障描述" name="bugDescribe">
                            <Input placeholder="请输入" allowClear />
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item label="故障等级" name="bugLevel">
                            <Select
                                placeholder="请选择故障类型"
                                options={[
                                    { label: '全部', value: '' },
                                    { label: '待定级', value: '待定级' },
                                    { label: 'P0', value: 'P0' },
                                    { label: 'P1', value: 'P1' },
                                    { label: 'P2', value: 'P2' },
                                    { label: 'P3', value: 'P3' },
                                    { label: 'P4', value: 'P4' },
                                    { label: 'P5', value: 'P5' },
                                ]}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item label="故障类型" name="bugType">
                            <Select
                                placeholder="请选择故障类型"
                                options={[
                                    { label: '全部', value: '' },
                                    { label: '技术自查', value: '技术自查' },
                                    { label: '业务反馈', value: '业务反馈' },
                                    { label: '数据监控', value: '数据监控' },
                                    { label: '自动化跑出', value: '自动化跑出' },
                                    { label: '其它', value: '其它' },
                                ]}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item label="故障状态" name="bugStatus">
                            <Select
                                placeholder="请选择故障状态"
                                options={[
                                    { label: '全部', value: '' },
                                    { label: '待处理', value: '待处理' },
                                    { label: '已解决', value: '已解决' },
                                    { label: '转产品', value: '转产品' },
                                ]}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item label="所属应用" name="belongApplication">
                            <Select
                                placeholder="请选择所属应用"
                                options={[
                                    { label: '全部', value: '' },
                                    { label: '订单', value: '订单' },
                                    { label: '采购', value: '采购' },
                                    { label: '仓库', value: '仓库' },
                                    { label: '商品', value: '商品' },
                                    { label: '结算', value: '结算' },
                                    { label: 'api', value: 'api' },
                                    { label: '营销', value: '营销' },
                                    { label: '会员', value: '会员' },
                                    { label: '前端', value: '前端' },
                                    { label: '其他', value: '其他' },
                                ]}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item label="故障时间" name="createTime">
                            <DatePicker.RangePicker placeholder={['开始日期', '结束日期']} style={{ width: '100%' }} />
                        </Form.Item>
                    </Col>
                    <Col span={24} style={{ textAlign: 'right' }}>
                        <Form.Item>
                            <Space size="small">
                                <Button type="primary" htmlType="submit" onClick={search.submit}>
                                    搜索
                                </Button>
                                <Button type="primary" onClick={search.reset}>
                                    重置
                                </Button>
                            </Space>
                        </Form.Item>
                    </Col>
                </Row>
                <div style={{ textAlign: 'left', marginBottom: 16}} >
                    <Button
                        type="primary"
                        className="mt-5 mb-5"
                        onClick={() => {
                            setIsEditInfo(false);
                            setRowItem({});
                            formModalSupplierInfo.modal.open();
                        }}
                    >
                        线上故障登记<br></br>
                    </Button>
                    <br />
                    <span className="form-span" style={{ color: 'red' }} >
                        注意: <br></br>
                    </span>
                    <div className="container">
                        <div className="leftDiv">
                            1、故障状态=处理中时，操作栏会出现【转bugfix】，可以直接创建bugfix需求； <br></br>
                            2、故障review及时跟进，在故障发生两周内结束；<br></br>
                        </div>
                        <div className="rightDiv">
                            <a href='https://theckb.yuque.com/staff-zil39d/smbib2/brnk0shr8nt405hb' target="_blank">故障定级参考文档</a><br></br>
                            <a href='https://theckb.yuque.com/staff-zil39d/smbib2/mtk7ozmf540nls1o' target="_blank">故障review文档地址</a><br></br>
                        </div>
                    </div>
                    
                </div>

                <Table
                    {...tableProps}
                    bordered
                    columns={columns}
                    pagination = {{...tableProps.pagination,showQuickJumper:true,
                        showTotal: (total) => `总计 ${total} `
                    }}
                    // rowKey="bugId"
                    locale={{ emptyText: '暂无数据' }}
                    scroll={{ x: 'calc(100vw + 1000px)' }}
                />
            </Form>
            <Modal
                destroyOnClose
                open={formModalSupplierInfo.isOpen}
                onOk={() => editSupplierInfo()}
                onCancel={() => {
                    formModalSupplierInfo.modal.close();
                }}
                title={isEditInfo ? '修改线上故障信息' : '新增线上故障'}
                className="supplierInfoModal"
                okText="确定"
                cancelText="取消"
                maskClosable={false}
            >
                <EditSupplierInfo formModal={formModalSupplierInfo} rowItem={rowItem} />
            </Modal>
            <Modal
                destroyOnClose
                open={formModalSupplierInfo1.isOpen}
                onOk={() => editDemandInfo()}
                onCancel={() => {
                    formModalSupplierInfo1.modal.close();
                }}
                title={"故障转为bugfix"}
                className="supplierInfoModal1"
                okText="确定"
                cancelText="取消"
                maskClosable={false}
            >
                <EditSupplierInfo1 formModal={formModalSupplierInfo1} rowItem={rowItem} bugfix={isBugfix} />
            </Modal>
        </div>
    );
};

export default SupplierList;
